<template>
  <div>
    <el-row type="flex" class="row-bg switch" justify="center">
      <el-col :span="6" data-v-7moor>
        <el-tooltip effect="dark" :content="msgVoice" :openDelay="200" transition="fade-leave" placement="bottom">
          <span
            class="sw-note iconfont"
            @click="toggle('note')"
            v-bind:class="{ 'icon-kaiguan2': note.isOn, 'icon-guan3': !note.isOn }"
          ></span>
        </el-tooltip>
      </el-col>
      <el-col :span="6" class="imStatus" data-v-7moor>
        <el-tooltip
          effect="dark"
          :content="openImLineUpNum"
          :openDelay="200"
          transition="fade-leave"
          placement="bottom"
        >
          <span
            class="sw-webchat iconfont"
            @click="toggle('webchat')"
            :class="[wIsOn === 'close' ? 'icon-guan' : 'icon-kaiguan1']"
          >
            <el-badge :value="wQueueNum" :max="99" class="webchatItem" v-show="wQueueNum > 0"> </el-badge>
          </span>
        </el-tooltip>
        <el-dropdown trigger="click" @command="imStatusChange" size="small" placement="bottom-start">
          <span class="el-dropdown-link"
            ><i
              :class="{
                'icon-zaixian': imStatusValue === $t('public.online'),
                'icon-manglu': imStatusValue !== $t('public.online')
              }"
              class="icon iconfont statusOutPoint"
            ></i
          ></span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in imStatusList"
              :key="index"
              :command="item"
              class="onlineDropdownItem"
              :class="{ onlineActive: imStatusValue === item.webStatusName }"
            >
              <i class="iconfont checkActive" :class="{ 'icon-xuanzhong': imStatusValue === item.webStatusName }"></i>
              {{ item.webStatusName }}
              <span
                :class="{
                  onlinePoint: item.webStatusName === $t('public.online'),
                  offPoint: item.webStatusName !== $t('public.online')
                }"
                class="statusPoint"
              ></span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="6" class="imStatus" data-v-7moor>
        <el-tooltip
          effect="dark"
          :content="orderStatusValue === 'order' ? '关闭自动接单' : '开启自动接单'"
          :openDelay="200"
          transition="fade-leave"
          placement="bottom"
        >
          <span
            class="sw-webchat iconfont"
            @click="toggle('automaticOrder')"
            :class="[orderStatusValue !== 'order' ? 'icon-gongdan-guanbi' : 'icon-gongdan-kaiqi']"
          >
          </span>
        </el-tooltip>
        <el-dropdown trigger="click" @command="automaticOrderStatusChange" size="small" placement="bottom-start">
          <span class="el-dropdown-link"
            ><i
              :class="[orderStatusValue !== 'order' ? 'icon-manglu' : 'icon-zaixian']"
              class="icon iconfont statusOutPoint"
            ></i
          ></span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in automaticOrderStatusList"
              :key="index"
              :command="item"
              class="onlineDropdownItem"
              :class="{ onlineActive: orderStatusValue === item.type }"
            >
              <i class="iconfont checkActive" :class="{ 'icon-xuanzhong': orderStatusValue === item.type }"></i>
              {{ item.orderStatusName }}
              <span
                :class="{
                  onlinePoint: item.orderStatusName === $t('public.online'),
                  offPoint: item.orderStatusName !== $t('public.online')
                }"
                class="statusPoint"
              ></span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="6" data-v-7moor v-if="!flag">
        <el-tooltip effect="dark" :content="openemail" :openDelay="200" transition="fade-leave" placement="bottom">
          <span
            class="sw-email iconfont"
            @click="toggle('email')"
            v-bind:class="{ 'icon-kaiguan': eIsOn, 'icon-guan2': !eIsOn }"
          >
            <el-badge :value="eQueueNum" :max="99" class="item" v-show="eQueueNum > 0"> </el-badge>
          </span>
        </el-tooltip>
      </el-col>
      <el-col :span="6" v-show="$store.state.phoneBarShow" data-v-7moor v-if="!flag">
        <el-tooltip
          effect="dark"
          :content="$t('softPhoneBar.queueLineUpNum')"
          :openDelay="200"
          transition="fade-leave"
          placement="bottom"
        >
          <span class="icon iconfont icon-suozaijinengzupaiduizongshu iconfont">
            <el-badge :value="cQueueNum" :max="99" class="item" v-show="cQueueNum > 0"> </el-badge>
          </span>
        </el-tooltip>
      </el-col>
      <el-col :span="6" v-show="$store.state.webrtc.showAutoAnswer" data-v-7moor>
        <el-tooltip
          effect="dark"
          :content="autoAnswer ? $t('softPhoneBar.closePhoneAutoAnswer') : $t('softPhoneBar.openPhoneAutoAnswer')"
          :openDelay="200"
          transition="fade-leave"
          placement="bottom"
        >
          <span
            class="icon iconfont"
            v-bind:class="{ 'icon-zidongjieting': autoAnswer, 'icon-guanbizidongjieting': !autoAnswer }"
            @click="toggle('webphone')"
          >
          </span>
        </el-tooltip>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'Switches',
  data() {
    return {
      note: {
        isOn: true
      },
      msgVoice: '',
      openImLineUpNum: '',
      openemail: '',
      imStatusValue: '',
      imStatusList: [
        { webStatusName: this.$t('public.online'), webStatusId: 'open' },
        { webStatusName: this.$t('public.offline'), webStatusId: 'close' }
      ],
      automaticOrderStatusList: [
        { orderStatusName: this.$t('public.online'), type: 'order' },
        { orderStatusName: this.$t('public.offline'), type: 'busy' },
      ],
      flag: this.$store.getters.isEcommerce ? true : false, // 是否是电商平台
      orderStatusValue: 'order'
    }
  },
  computed: {
    ...mapState({
      wIsOn: (state) =>
        state.session.user.uversion && state.session.user.uversion === 'monitor' ? 'close' : state.webchat.isOn,
      wQueueNum: (state) => state.webchat.queueNum,
      eIsOn: (state) =>
        state.session.user.uversion && state.session.user.uversion === 'monitor' ? false : state.email.isOn,
      autoAnswer: (state) => state.webrtc.autoAnswer,
      eQueueNum: (state) => state.email.queueNum,
      cQueueNum: (state) => state.cti.globalLet.queueNumber,
      orderMonitor: (state) => state.order.orderMonitor
    })
  },
  watch: {
    wIsOn() {
      this.imStatusValue = this.wIsOn === 'close' ? this.$t('public.offline') : this.$t('public.online')
    },
    orderMonitor: {
      deep: true,
      handler() {
        let user = this.$store.state.session.user
        if (user._id == this.$store.state.order.orderMonitor.currentUserId) {
          this.orderStatusValue = this.$store.state.order.orderMonitor.isOn
          console.log(this.orderStatusValue)
        }
        this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
          if (res) {
            res.forEach(item => {
              if (item._id === this.$store.state.order.orderMonitor.currentUserId) {
                item.autoOrderInitStatus = this.$store.state.order.orderMonitor.isOn
              }
            })
            this.$updateCache('agents', res)
          }
        })
      }
    }
  },
  methods: {
    imStatusChange(value) {
      let lastWebStatus = window.sessionStorage.getItem('webStatusConfig')
        ? JSON.parse(window.sessionStorage.getItem('webStatusConfig')).webStatusId
        : ''
      if (lastWebStatus === value.webStatusId) {
        return
      }
      this.imStatusValue = value.webStatusName
      this.toggle('webchat', value)
    },
    automaticOrderStatusChange(event) {
      if (event.type === this.orderStatusValue) return
      this.toggle('automaticOrder', event)
    },
    toggleCloseSuccess(value) {
      if (window.sessionStorage.webChatIsOn === 'open') {
        this.imStatusValue = this.$t('public.online')
      } else {
        if (window.sessionStorage.getItem('webStatusConfig')) {
          this.imStatusValue = JSON.parse(window.sessionStorage.getItem('webStatusConfig')).webStatusName
        } else {
          this.imStatusValue = this.$t('public.offline')
        }
      }
    },
    toggle(flag, value) {
      let user = this.$store.state.session.user
      switch (flag) {
        case 'note':
          this.note.isOn = !this.note.isOn
          let loginInfo = JSON.parse(window.sessionStorage.getItem('loginData'))
          this.msgVoice = this.note.isOn ? this.$t('softPhoneBar.openMsg') : this.$t('softPhoneBar.closeMsg')
          let form = {}
          form.isOn = this.note.isOn
          form.loginName = loginInfo.loginName
          window.localStorage.setItem(loginInfo.loginName, JSON.stringify(form))
          break
        case 'automaticOrder':
          this.$store
            .dispatch('updateAutoOrderInitStatus', {
              _id: user._id,
              autoOrderInitStatus: this.orderStatusValue,
              type: 'agentAction'
            })
            .then()
          break
        case 'webchat':
          if (user.uversion && user.uversion === 'monitor') {
            this.$message.error(this.$t('public.monitorVerTip'))
            return
          }
          // let status = this.$store.state.webchat.isOn === 'close' ? 'open' : 'close'
          let status
          if (this.$store.state.webchat.isOn === 'close') {
            if (value) {
              if (value.webStatusId !== 'open') {
                status = 'close'
              } else {
                status = 'open'
              }
            } else {
              status = 'open'
            }
          } else {
            status = 'close'
          }
          if (status === 'open') {
            let statusToogleNewl = value ? value.webStatusId : 'open'
            this.$store
              .dispatch('updateWebchatAutoClaimStatus', {
                status: status,
                type: 'agentAction',
                chatStatusDetail: statusToogleNewl
              })
              .then((req) => {
                if (req && req.success) {
                  window.sessionStorage.setItem('webChatIsOn', status)
                  let newStatus = {}
                  if (value) {
                    newStatus = value
                  } else {
                    newStatus.webStatusName = this.$t('public.online')
                    newStatus.webStatusId = 'open'
                  }
                  window.sessionStorage.setItem('webStatusConfig', JSON.stringify(newStatus))
                  this.openImLineUpNum =
                    window.sessionStorage.webChatIsOn === 'open'
                      ? this.$t('softPhoneBar.imLineUpNum')
                      : this.$t('softPhoneBar.closeImLineUpNum')
                  if (window.sessionStorage.webChatIsOn === 'open') {
                    this.imStatusValue = this.$t('public.online')
                  }
                } else {
                  this.imStatusValue = JSON.parse(window.sessionStorage.getItem('webStatusConfig')).webStatusName
                }
              })
          } else {
            let statusToogleNewl = value ? value.webStatusId : 'close'
            this.$store.dispatch('judgeMobileClient', {}).then((res) => {
              if (res && res.closeMobile) {
                // 判断移动端领取会话是否开启
                this.$confirm(this.$t('webchat.judgeMobileClient'), '', {
                  confirmButtonText: this.$t('public.confirm'),
                  cancelButtonText: this.$t('public.cancel'),
                  cancelButtonClass: 'primary_btn',
                  confirmButtonClass: 'primary_btn',
                  type: 'warning'
                })
                  .then(() => {
                    this.$store
                      .dispatch('updateWebchatAutoClaimStatus', {
                        status: status,
                        closeMobile: true,
                        type: 'agentAction',
                        chatStatusDetail: statusToogleNewl
                      })
                      .then((req) => {
                        if (req && req.success) {
                          window.sessionStorage.setItem('webChatIsOn', status)
                          let newStatus = {}
                          if (value) {
                            window.sessionStorage.setItem('webStatusConfig', JSON.stringify(value))
                            this.toggleCloseSuccess(value)
                          } else {
                            this.imStatusValue = this.$t('public.offline')
                            let newStatus = {
                              webStatusName: this.$t('public.offline'),
                              webStatusId: 'close'
                            }
                            window.sessionStorage.setItem('webStatusConfig', JSON.stringify(newStatus))
                          }
                          this.openImLineUpNum =
                            window.sessionStorage.webChatIsOn === 'open'
                              ? this.$t('softPhoneBar.imLineUpNum')
                              : this.$t('softPhoneBar.closeImLineUpNum')
                        } else {
                          this.imStatusValue = JSON.parse(
                            window.sessionStorage.getItem('webStatusConfig')
                          ).webStatusName
                        }
                      })
                  })
                  .catch(() => {
                    this.$store
                      .dispatch('updateWebchatAutoClaimStatus', {
                        status: status,
                        closeMobile: false,
                        type: 'agentAction',
                        chatStatusDetail: statusToogleNewl
                      })
                      .then((req) => {
                        if (req && req.success) {
                          window.sessionStorage.setItem('webChatIsOn', status)
                          let newStatus = {}
                          if (value) {
                            window.sessionStorage.setItem('webStatusConfig', JSON.stringify(value))
                            this.toggleCloseSuccess(value)
                          } else {
                            this.imStatusValue = this.$t('public.offline')
                            let newStatus = {
                              webStatusName: this.$t('public.offline'),
                              webStatusId: 'close'
                            }
                            window.sessionStorage.setItem('webStatusConfig', JSON.stringify(newStatus))
                          }
                          this.openImLineUpNum =
                            window.sessionStorage.webChatIsOn === 'open'
                              ? this.$t('softPhoneBar.imLineUpNum')
                              : this.$t('softPhoneBar.closeImLineUpNum')
                        } else {
                          this.imStatusValue = JSON.parse(
                            window.sessionStorage.getItem('webStatusConfig')
                          ).webStatusName
                        }
                      })
                  })
              } else {
                this.$store
                  .dispatch('updateWebchatAutoClaimStatus', {
                    status: status,
                    type: 'agentAction',
                    chatStatusDetail: statusToogleNewl
                  })
                  .then((req) => {
                    if (req && req.success) {
                      window.sessionStorage.setItem('webChatIsOn', status)
                      if (value) {
                        window.sessionStorage.setItem('webStatusConfig', JSON.stringify(value))
                        this.toggleCloseSuccess(value)
                      } else {
                        this.imStatusValue = this.$t('public.offline')
                        let newStatus = {
                          webStatusName: this.$t('public.offline'),
                          webStatusId: 'close'
                        }
                        window.sessionStorage.setItem('webStatusConfig', JSON.stringify(newStatus))
                      }
                      this.openImLineUpNum =
                        window.sessionStorage.webChatIsOn === 'open'
                          ? this.$t('softPhoneBar.imLineUpNum')
                          : this.$t('softPhoneBar.closeImLineUpNum')
                    } else {
                      this.imStatusValue = JSON.parse(window.sessionStorage.getItem('webStatusConfig')).webStatusName
                    }
                  })
              }
            })
          }
          break
        case 'email':
          if (user.uversion && user.uversion === 'monitor') {
            this.$message.error(this.$t('public.monitorVerTip'))
            return
          }
          let emailStatus = this.$store.state.email.isOn ? 'close' : 'open'
          this.$store.dispatch('updateEmailAutoClaimStatus', { emailStatus: !this.eIsOn }).then((req) => {
            if (req && req.success) {
              window.sessionStorage.setItem('emailChatIsOn', emailStatus)
              this.openemail = this.$store.state.email.isOn
                ? this.$t('softPhoneBar.emailLineUpNum')
                : this.$t('softPhoneBar.closeEmailLineUpNum')
            }
          })
          break
        case 'webphone':
          this.$store.commit('webrtc/SET_AUTO_ANSWER', !this.autoAnswer)
          break
      }
    }
  },
  mounted() {
    this.orderStatusValue = this.$store.state.session.user.autoOrderInitStatus === undefined ? 'busy' : this.$store.state.session.user.autoOrderInitStatus
    let loginData = window.sessionStorage.getItem('loginData')
    if (loginData) {
      // 获取用户存储的开关状态
      let loginInfo = JSON.parse(loginData)
      let JsonString = window.localStorage.getItem(loginInfo.loginName)
      let webSoftTelephone = this.$store.state.session.user.webSoftTelephone ? true : false
      this.$store.commit('webrtc/SET_AUTO_ANSWER', webSoftTelephone)
      if (JsonString) {
        let obj = JSON.parse(JsonString)
        let bool = obj.isOn
        this.note.isOn = bool
        this.msgVoice = this.note.isOn ? this.$t('softPhoneBar.openMsg') : this.$t('softPhoneBar.closeMsg')
      } else {
        this.msgVoice = this.note.isOn ? this.$t('softPhoneBar.openMsg') : this.$t('softPhoneBar.closeMsg')
      }
    }
    let webChatIsOn = window.sessionStorage.getItem('webChatIsOn')
    this.$store.dispatch('queryEnableWebStatus', {}).then((res) => {
      if (res.success && res.isEnableWebStatus) {
        let newData = res.data.filter((item) => {
          return item.isEnable === '1'
        })
        this.imStatusList = this.imStatusList.concat(newData)
        let webStatusConfig = window.sessionStorage.getItem('webStatusConfig')
        if (webStatusConfig) {
          let newWebStatusConfig = this.imStatusList.filter((item) => {
            return JSON.parse(webStatusConfig).webStatusId === item.webStatusId
          })
          if (newWebStatusConfig && newWebStatusConfig.length > 0 && webStatusConfig) {
            window.sessionStorage.setItem('webStatusConfig', JSON.stringify(newWebStatusConfig[0]))
            this.imStatusValue = newWebStatusConfig[0].webStatusName
          } else {
            this.imStatusValue = JSON.parse(webStatusConfig).webStatusName
          }
        } else {
          this.imStatusValue =
            this.$store.state.webchat.isOn === 'open' ? this.$t('public.online') : this.$t('public.offline')
        }
      }
    })
    if (webChatIsOn) {
      this.openImLineUpNum =
        window.sessionStorage.webChatIsOn === 'open'
          ? this.$t('softPhoneBar.imLineUpNum')
          : this.$t('softPhoneBar.closeImLineUpNum')
      this.imStatusValue =
        window.sessionStorage.webChatIsOn === 'open' ? this.$t('public.online') : this.$t('public.offline')
    } else {
      this.openImLineUpNum =
        this.$store.state.webchat.isOn === 'open'
          ? this.$t('softPhoneBar.imLineUpNum')
          : this.$t('softPhoneBar.closeImLineUpNum')
      this.imStatusValue =
        this.$store.state.webchat.isOn === 'open' ? this.$t('public.online') : this.$t('public.offline')
    }
    let newWebStatusConfig = window.sessionStorage.getItem('webStatusConfig')
    let emailChatIsOn = window.sessionStorage.getItem('emailChatIsOn')
    if (emailChatIsOn) {
      var emailState = false
      if (emailChatIsOn === 'open') {
        emailState = true
      }
      this.$store.dispatch('updateEmailAutoClaimStatus', { emailStatus: emailState }).then((req) => {
        if (req && req.success) {
          this.openemail =
            window.sessionStorage.emailChatIsOn === 'open'
              ? this.$t('softPhoneBar.emailLineUpNum')
              : this.$t('softPhoneBar.closeEmailLineUpNum')
        }
      })
    } else {
      this.openemail = this.$store.state.email.isOn
        ? this.$t('softPhoneBar.emailLineUpNum')
        : this.$t('softPhoneBar.closeEmailLineUpNum')
    }
  }
}
</script>
<style scoped lang="stylus">
@import "../../../assets/common.styl"
.item
  margin-top -65px
  margin-left 8px
.webchatItem
  position absolute
  top -9px
  left 10px
.switch
  float left
  height 53px
  margin 0 8px 0 0
  .el-col
    width 24px
    height 24px
    margin 15px 6px 0 0
    color $c-main
    cursor pointer
    span
      display block
      height 100%
      font-size 20px
  .imStatus
    width 100%
    margin-right -8px
    span
      display inline-block
    .el-dropdown
      font-size 20px !important
    .el-dropdown-link
      width 12px
      font-size 20px
      color #595959
      vertical-align middle
      padding-left 5px
  .icon-guan3
    color #ff6b6b
  .icon-guan
    color #ff6b6b
  .icon-guan2
    color #ff6b6b
  .icon-guanbizidongjieting
    color #ff6b6b
  .sw-webchat
    // vertical-align middle
    position relative
.statusPoint
  width 5px
  height 5px
  display inline-block
  border-radius 50%
  margin-left 5px
  vertical-align middle
.statusOutPoint
  width 10px
  height 10px
  display inline-block
  border-radius 50%
  margin-left -2px
  vertical-align middle
  line-height 10px
  text-align center
  font-size 10px
  color #ffffff
  padding-right 1px
  padding-top 1px
.onlinePoint
  background #41B27F
.offPoint
  background #FF9100
.icon-manglu
  background #FF9100
  color #ffffff
.icon-zaixian
  background #41B27F
.checkActive
  font-size 12px
  width 12px
  display inline-block
  color #459AE9
.onlineActive
  background #EDF5FD
  color #459AE9
.icon-gongdan-kaiqi
  color #459AE9
.icon-gongdan-guanbi
  color #ff6b6b
</style>
